package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.MiniStockSubject;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MiniSubject;
import com.ruoyi.system.service.IMiniSubjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题材Controller
 * 
 * @author ruoyi
 * @date 2023-11-01
 */
@RestController
@RequestMapping("/system/subject")
public class MiniSubjectController extends BaseController
{
    @Autowired
    private IMiniSubjectService miniSubjectService;

    /**
     * 查询题材列表
     */
    @PreAuthorize("@ss.hasPermi('system:subject:list')")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody MiniSubject miniSubject)
    {
        List<MiniSubject> list = miniSubjectService.selectMiniSubjectList(miniSubject);
        return success(list);
    }
    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:subject:list')")
    @GetMapping("/list/exclude/{subjectId}")
    public AjaxResult excludeChild(@PathVariable(value = "subjectId", required = false) Long subjectId)
    {
        List<MiniSubject> subjects = miniSubjectService.selectMiniSubjectList(new MiniSubject());
        subjects.removeIf(d -> d.getSubjectId().intValue() == subjectId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), subjectId + ""));
        return success(subjects);
    }
    /**
     * 导出题材列表
     */
    @PreAuthorize("@ss.hasPermi('system:subject:export')")
    @Log(title = "题材", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MiniSubject miniSubject)
    {
        List<MiniSubject> list = miniSubjectService.selectMiniSubjectList(miniSubject);
        ExcelUtil<MiniSubject> util = new ExcelUtil<MiniSubject>(MiniSubject.class);
        util.exportExcel(response, list, "题材数据");
    }

    /**
     * 获取题材详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:subject:query')")
    @GetMapping(value = "/{subjectId}")
    public AjaxResult getInfo(@PathVariable("subjectId") Long subjectId)
    {
        return success(miniSubjectService.selectMiniSubjectBySubjectId(subjectId));
    }

    /**
     * 新增题材
     */
    @PreAuthorize("@ss.hasPermi('system:subject:add')")
    @Log(title = "题材", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MiniSubject miniSubject)
    {
        if (!miniSubjectService.checkSubjectNameUnique(miniSubject))
        {
            return error("新增题材'" + miniSubject.getName() + "'失败，题材名称已存在");
        }
        if (miniSubjectService.checkSubjectHaveStock(miniSubject.getParentId())){
            return error("新增题材'" + miniSubject.getName() + "'失败，有股票的题材不能添加子题材");
        }
        miniSubject.setCreateBy(getUsername());
        miniSubject.setCreateTime(DateUtils.getNowDate());
        return toAjax(miniSubjectService.insertMiniSubject(miniSubject));
    }

    /**
     * 修改题材
     */
    @PreAuthorize("@ss.hasPermi('system:subject:edit')")
    @Log(title = "题材", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MiniSubject miniSubject)
    {
        Long subjectId = miniSubject.getSubjectId();
        //miniSubjectService.checkDeptDataScope(subjectId);
        if (!miniSubjectService.checkSubjectNameUnique(miniSubject))
        {
            return error("修改题材'" + miniSubject.getName() + "'失败，题材名称已存在");
        }
        else if (miniSubject.getParentId().equals(subjectId))
        {
            return error("修改题材'" + miniSubject.getName() + "'失败，上级题材不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, miniSubject.getStatus()) && miniSubjectService.selectNormalChildrenSubjectById(subjectId) > 0)
        {
            return error("该题材包含未停用的子题材！");
        }
        miniSubject.setUpdateBy(getUsername());
        return toAjax(miniSubjectService.updateMiniSubject(miniSubject));
    }

    /**
     * 删除题材
     */
    @PreAuthorize("@ss.hasPermi('system:subject:remove')")
    @Log(title = "题材", businessType = BusinessType.DELETE)
	@DeleteMapping("/{subjectId}")
    public AjaxResult remove(@PathVariable Long subjectId)
    {
        if (miniSubjectService.hasChildBySubjectId(subjectId))
        {
            return warn("存在下级题材,不允许删除");
        }
        if (miniSubjectService.checkSubjectHaveStock(subjectId))
        {
            return warn("题材存在股票,不允许删除");
        }
        return toAjax(miniSubjectService.deleteMiniSubjectBySubjectId(subjectId));
    }
    /**
     * 查询题材是否有子节点
     */
    @PreAuthorize("@ss.hasPermi('system:subject:list')")
    @GetMapping("/hasChild/{subjectId}")
    public AjaxResult hasChild(@PathVariable Long subjectId) {
        List<MiniSubject> list = miniSubjectService.list(Wrappers.<MiniSubject>lambdaQuery()
                .eq(MiniSubject::getParentId, subjectId)
                .eq(MiniSubject::getStatus, 0)
                .eq(MiniSubject::getDelFlag, 0));

        return success(CollUtil.isEmpty(list) ? 0 : 1);
    }

    /**
     * 题材添加多个股票
     * @param stockSubject
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:stock:add')")
    @Log(title = "题材添加多个股票", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSubjectStock")
    public AjaxResult updateSubjectStock(@RequestBody MiniStockSubject stockSubject){
        return toAjax(miniSubjectService.updateSubjectStock(stockSubject));
    }

    /**
     * 导入题材
     */
    @PreAuthorize("@ss.hasPermi('system:subject:import')")
    @Log(title = "题材", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        return miniSubjectService.importData(file, updateSupport,getUsername(),DateUtils.getNowDate());
    }
}
